package com.glacier.common.core.domain;

import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * date 2022-11-06 14:09
 * http元数据
 *
 * @author glacier
 * @version 1.0
 */
public class HttpRange implements Serializable {
	
	private static final long serialVersionUID = 9157195883404925559L;
	private static final Pattern PATTERN = Pattern.compile("^bytes=(\\d+)-(\\d+)?$");
	/**
	 *
	 */
	private final String range;
	/**
	 * 文件大小
	 */
	private final long fileLength;
	/**
	 * 记录已下载文件大小
	 */
	private long pastLength = 0L;
	/**
	 * 记录客户端需要下载的字节段的最后一个字节偏移量（比如bytes=27000-39000，则这个值是为39000）
	 */
	private long toLength = 0L;
	/**
	 * 客户端请求的字节总量
	 */
	private long contentLength = 0L;
	
	public HttpRange(String range, long fileLength) {
		this.range = range;
		this.fileLength = fileLength;
	}
	
	public String getRange() {
		return range;
	}
	
	public long getPastLength() {
		return pastLength;
	}
	
	public long getToLength() {
		return toLength;
	}
	
	public long getContentLength() {
		return contentLength;
	}
	
	public long getFileLength() {
		return fileLength;
	}
	
	/**
	 * 判断是否为断点续传
	 *
	 * @return
	 */
	public boolean isContinuable() {
		return range != null && !range.isBlank();
	}
	
	/**
	 * 解析range
	 *
	 * @return
	 */
	public HttpRange parseRange() {
		// 默认
		toLength = fileLength - 1;
		contentLength = fileLength;
		if (!isContinuable()) {
			Matcher matcher = PATTERN.matcher(range);
			if (matcher.find()) {
				pastLength = Integer.parseInt(matcher.group(1));
				String endStr = matcher.group(2);
				if (endStr != null && !endStr.isBlank()) {
					toLength = Math.min(Integer.parseInt(endStr), fileLength - 1);
				}
			}
			// 客户端请求的是 1275856879-1275877358 之间的字节
			contentLength = toLength - pastLength + 1;
		}
		return this;
	}
	
	/**
	 * 组装 Content-Range
	 *
	 * @return
	 */
	public String buildContentRange() {
		return "bytes " + pastLength + "-" + toLength + "/" + fileLength;
	}
}
